package org.company.earth.util;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtil {
    
    private static String CHARSET = "UTF-8";
    
    private static XmlUtil instance = null;
    
    private XmlUtil () {
        
    }
    
    public static XmlUtil getInstance() {
        if(instance == null) {
            instance = new XmlUtil();
        }
        return instance;
    }
    
    public Document createDocument(String rootName) {
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding(CHARSET);
        document.addElement(rootName);
        return document;
    }
    
    public Document parse(String docText,String charset) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(new ByteArrayInputStream(docText.getBytes(charset)));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return doc;
    }
    
    public Document parse(String docText) throws DocumentException {
        String charset = Charset.defaultCharset().displayName();
        return this.parse(docText, charset);
    }
    
    /**
     * 返回结果集doc对象
     * @method createDocument
     * @param retCode
     * @param retMsg
     * @return
     */
    public Document createDocument(String retCode,String retMsg) {
        Document doc = this.createDocument("ROOT");
        Element root = doc.getRootElement();
        root.addElement("retCode").setText(retCode);
        root.addElement("retMsg").setText(retMsg);
        return doc;
    }
}
